package br.com.registrofinancas.view;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import br.com.registrofinancas.R;
import br.com.registrofinancas.database.CategoriasDAO;
import br.com.registrofinancas.database.DataSource;
import br.com.registrofinancas.database.MovimentosDAO;

public class BackupActivity extends Activity implements OnClickListener {

	private static final String DATABASE_NAME = "financas.db";
	private static String DB_PATH="/data/backup/databases/";
	private Dialog dialog;
	private Intent intent;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_exclude_backup);
		createDialog();
	}

	@Override
	public void onClick(View v) {
		
		if(v.getId() == R.id.backup_exclude_dialog_bt_OK){
			try {
				copiarDataBase();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
			goBack();
		}else
		{
			dialog.dismiss();
			goBack();
		}
		
	}
	
	public void createDialog()
	{
		dialog = new Dialog(this);
		dialog.setContentView(R.layout.backup_exclude_dialog);
		dialog.setTitle("Backup");
		TextView tvMessage = (TextView) dialog.findViewById(R.id.backup_exlude_dialog_tx_message);
		tvMessage.setText("Deseja realizar o backup do banco");
		Button buttonOk = (Button) dialog.findViewById(R.id.backup_exclude_dialog_bt_OK);
		Button buttonCancel = (Button) dialog.findViewById(R.id.backup_exclude_dialog_bt_Cancel);
		buttonOk.setOnClickListener(this);
		buttonCancel.setOnClickListener(this);
		dialog.show();
	}
	
	public void goBack()
	{
		intent = new Intent(this, MenuActivity.class);
		startActivity(intent);
	}
	
	public void copiarDataBase() throws IOException
	{
		  
      InputStream myInput = this.getAssets().open(DATABASE_NAME);
      String outFileName = DB_PATH + DATABASE_NAME;
      OutputStream myOutput = new FileOutputStream(outFileName);
 
      byte[] buffer = new byte[1024];
      int length;
      while ((length = myInput.read(buffer))>0)
      {
    	  myOutput.write(buffer, 0, length);
      }
 
      myOutput.flush();
      myOutput.close();
      myInput.close();
	 
	}
	
			
}
